// LZL Local
// const HOST = 'http://192.168.181.170:8088/channel-openapi'
// SJHLocal
// const HOST = 'http://192.168.190.68:8888/channel-openapi'
// Test
// const HOST = 'http://openapi.devch.qiaofangcloud.cn/channel-openapi'
// UAT
// const HOST = 'https://apich.qfstatic.com/channel-openapi'
// Online
const HOST = 'https://qiaoxin.apich.qfstatic.com/channel-openapi'
// 注释
// 1.每次定制化，根据不同环境修改为不同的companyUuids
// 2.修改data里面的navigationBarTitleText和logo
// 3.修改app.wpy文件里面的window的navigationBarTitleText
// 4.修改project.configw.json文件里的appID
const customizedCompanyUuids = ['2b53ec3f-9c83-11e8-b93d-000c2979eb04', '9e4e724b-b109-11e8-89a5-005056889b83', 'bd5a3f61-1c24-4d33-88d0-345808de5084','4656d480-d49d-4c63-a14e-077178abdd80', '71c6ad7d-c8fa-45e8-be6c-a1cf63c5fb60']
// 定制化
const customized = true
// 非定制化
// const customized = false
let valid = true
export default {
  data: {
    mixin: 'MixinText',
    time: null,
    HOST: HOST,
    // navigationBarTitleText: '楚居客',
    // navigationBarTitleText: '闪卖',
    // navigationBarTitleText: '好房快销',
    navigationBarTitleText: '鲨鱼好房',
    // logo: 'https://7465-test-8g6x0jbcd32d6173-1304478274.tcb.qcloud.la/henIconOld.png',
    // logo: '/static/images/Icon.png',
    logo: 'https://image.qfstatic.com//channel/20210323/b68aa373-e3d4-4eaf-b0aa-124e0bd59bef.png',
    // henxinFlag: true,
    henxinFlag: false,
  },
  methods: {
    // 将最新openId发给后端，更新数据库里的用户最近登录的手机的openId，确保模板消息发送到正确的手机
     getOpenId(){
      let authorization = wx.getStorageSync('authorization')
      let allAuthorization = wx.getStorageSync('allAuthorization')
      if(authorization){
        if(authorization.openId){
          let params={openId:authorization.openId,loginType: '7', userId: authorization.partnerId,  companyUuid: authorization.companyUuid}
          wx.request({
            url: HOST + '/weixin/refreshOpenId',
            data: params,
            method:'post',
            header: {
              loginType: '7',
              companyUuid: authorization.companyUuid || '',
              wxOpenid: authorization.openId|| '',
              userId: authorization.partnerId || '',
              accountType: authorization.accountType
            }
          })
        }else{
          wx.login({
            success: (res) => {
              let params={loginType: '7', userId: authorization.partnerId,  companyUuid: authorization.companyUuid, data:{code:res.code}}
              wx.request({
                url: HOST + '/weixin/refreshOpenIdByJsCode',
                data: params,
                method:'post',
                header: {
                  loginType: '7',
                  companyUuid: authorization.companyUuid || '',
                  wxOpenid: authorization.openId || '',
                  userId: authorization.partnerId || '',
                  accountType: authorization.accountType
                },
                success:res=>{
                  res.data.msg=res.data.msg || ''
                  authorization.openId=res.data.msg
                  allAuthorization.forEach(item=>item.openId=res.data.msg)
                  wx.setStorageSync('authorization',authorization)
                  wx.setStorageSync('allAuthorization',allAuthorization)
                }
              })
            }
          });
        }        
      }    
    },    
    request (data, param = {}, showLoading = true, isNull = true) {
      let url = data.url.indexOf('http') > -1 ? data.url : HOST + data.url
      let params = {}
      let query = {}
      showLoading && this.toast('加载中...', 'loading', 10000)
      const authorization = wx.getStorageSync('authorization') || {}
      if (Object.keys(param).length > 0) {
        if (isNull) {
          for (let i in param) {
            if (param[i] !== void 0 && param[i] !== "" && param[i] !== null) {
              query[i] = param[i]
            }
          }
        } else {
          query = param
        }
        params = { ...params, loginType: '7', userId: authorization.partnerId, data: query, companyUuid: authorization.companyUuid || '' }
      } else {
        params = { ...params, loginType: '7', userId: authorization.partnerId, companyUuid: authorization.companyUuid || '' }
      }
      if (customized) {
        params = { ...params, companyUuids: customizedCompanyUuids }
      }
      // console.log(url, query, data.type);
      return new Promise((resolve, reject) => {
        wx.request({
          url: url,
          data: params,
          method: data.type,
          header: {
            loginType: '7',
            companyUuid: authorization.companyUuid || '',
            wxOpenid: authorization.openId || '',
            userId: authorization.partnerId || '',
            accountType: authorization.accountType
          },
          success (res) {
            // console.log(res);
            switch (res.statusCode) {
              case 401:
                // toast('请重新登录','none')
                wx.clearStorage();
                wx.reLaunch({ url: '/pages/login/quickLogin' })
                wx.hideToast()
                break
              case 200:
                if(res.data.code === '2'){
                  // 此种情况为重复点击，则不再调用
                  resolve()
                }else if (res.data.code === '1') {
                  if (showLoading) {
                    wx.hideToast()
                  }
                  resolve(res.data.data || 1)
                } else if (res.data.code === '0' || res.data.code === '99998') {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 3000,
                  })
                  resolve()
                } else if (res.data.code === '-1') {
                  wx.hideToast()
                  wx.clearStorage();
                  wx.reLaunch({ url: '/pages/login/quickLogin' })
                } else {
                  wx.showToast({
                    title: "服务器繁忙，请稍后再试...",
                    icon: 'none',
                    duration: 3000,
                  })
                }
                // reject(res.data)
                break
              default:
                wx.showToast({
                  title: '服务器繁忙，请稍后再试。。。',
                  icon: 'none',
                  duration: 3000,
                })
            }
          },
          fail (err) {
            wx.showToast({
              title: "服务器繁忙中，请稍后再试",
              icon: 'none',
              duration: 3000,
            })
          },
          complete (res) {
            // wx.hideToast()
          }
        })
      })
    },
    requestPage (data, param = {}, showLoading = true,partnerId='',companyUuid='') {
      let url = data.url.indexOf('http') > -1 ? data.url : HOST + data.url
      let params = {}
      showLoading && this.toast('加载中...', 'loading', 10000)
      const authorization = wx.getStorageSync('authorization') || {}
      for (let i in param) {
        let query = {}
        if (typeof (param[i]) === 'object') {
          for (let j in param[i]) {
            if (param[i][j] !== void 0 && param[i][j] !== "" && param[i][j] !== null) {
              query[j] = param[i][j]
            }
          }
        }
        param[i] = query
      }
      params = { ...params, ...param, loginType: '7', userId: partnerId  || authorization.partnerId , companyUuid: companyUuid || authorization.companyUuid   }
      if (customized) {
        params = { ...params, companyUuids: customizedCompanyUuids }
      }
      return new Promise((resolve, reject) => {
        wx.request({
          url: url,
          data: params,
          method: data.type,
          header: {
            loginType: '7',
            companyUuid: companyUuid ||authorization.companyUuid,
            wxOpenid: authorization.openId || '',
            userId: partnerId || authorization.partnerId,
            accountType: authorization.accountType
          },
          success (res) {
            // console.log(res);
            switch (res.statusCode) {
              case 401:
                // toast('请重新登录','none')
                wx.clearStorage();
                wx.reLaunch({ url: '/pages/login/quickLogin' })
                wx.hideToast()
                break
              case 200:
                if (res.data.code === '1') {
                  resolve(res.data.data || 1)
                  if (showLoading) {
                    wx.hideToast()
                  }
                } else if (res.data.code === '0' || res.data.code === '99998') {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 3000,
                  })
                  // resolve()
                } else if (res.data.code === '-1') {
                  wx.hideToast()
                  wx.clearStorage();
                  wx.reLaunch({ url: '/pages/login/quickLogin' })
                } else {
                  wx.showToast({
                    title: "服务器繁忙，请稍后再试...",
                    icon: 'none',
                    duration: 3000,
                  })
                }
                // reject(res.data)
                break
              default:
                wx.showToast({
                  title: '服务器繁忙，请稍后再试。。。',
                  icon: 'none',
                  duration: 3000,
                })
            }
          },
          fail (err) {
            wx.showToast({
              title: "服务器繁忙中，请稍后再试",
              icon: 'none',
              duration: 3000,
            })
          },
          complete (res) {
            // wx.hideToast()
          }
        })
      })
    },
    toast (a, b, c) {
      let obj = {
        title: a,
        icon: b || 'none',
        duration: c || 2000
      }
      wx.showToast(obj)
    },
    // 防抖
    debounce (fn, params, interval) {
      interval = interval || 1000
      clearTimeout(this.time);
      this.time = setTimeout(() => {
        fn.call(this, params);
      }, interval);
    },
    // 节流
    throttle (fn, params, interval) {
      interval = interval || 3000
      if (!valid) {
        return false
      }
      valid = false
      fn.call(this, params);
      setTimeout(() => {
        valid = true
      }, interval);
    },
    formatTime (time) {
      if (!time) {
        return ''
      } else {
        var date = new Date(time)
        var year = date.getFullYear()
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var mins = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        // var milli = date.getMilliseconds()
        return year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + sec
      }

    },
    getWXCode(){
      return new Promise((resolve, reject) => {
        wx.login({
          success: (res) => {
            resolve(res.code);
          },
          fail: (err) => {
            reject('')
          },
        });
      });
    }
  },
}
